// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  console.log("event=",event)
  let c = event.category
  let start = event.start || 0
  console.log("start=",start)

  let collection = cloud.database().collection("resources")

  r = await collection.where({
    category: c
  }).skip(start).limit(10).get().then(res =>{
    console.log("res=",res)
    if(res){
      return res.data
    }
  })

  let t = Array()
  if(r.length != 0){
    //遍历
    for(let i = 0; i < r.length; i++){
      //需要标题、作者、时间、图片、ID
      let j = r[i] //分别是每个对象
      let time = j.date
      if(time){
        time = "" + time.getFullYear().toString() + "-" + (time.getMonth()+1).toString() + "-" + time.getDate().toString() + ' ' + time.getHours().toString() + ":" + time.getMinutes().toString()
      }else{
        time = ''
      }
      
      t.push({
        "_id": j._id,
        "title": j.title,
        "editor": j.editor,
        "date": time,
        "image": j["image"] || '',
        "type": j.type,
        "source": j['source'] || ''
      })
    }
    console.log("result=", t)
  }
  
  return t
}